package com.yangle.bootdemo.service.impl;

import com.yangle.bootdemo.pojo.Article;
import com.yangle.bootdemo.repository.ArticleRepository;
import com.yangle.bootdemo.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public Map<String, Object> findAllArticle(int page, int pageSize) {
        Map<String,Object> map = new HashMap<>();
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        Pageable pageable = PageRequest.of(page-1,pageSize,sort);
        Page<Article> all = articleRepository.findAll(pageable);
        map.put("list",all.getContent());
        map.put("total",all.getTotalPages());
        map.put("cPage",page);
        if (page - 1 <= 0){
            map.put("prPage",page);
        }else{
            map.put("prPage",page -1);
        }
        if (page + 1 > all.getTotalPages()) {
            map.put("laPage", page);
        }else{
            map.put("laPage", page + 1);
        }
        return map;
    }
}
